﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using IOPath = System.IO.Path;

namespace LightCAD.MathLib
{
    public class TimePoint
    {
        public string Key;
        public string Text;
        public DateTime Time;
    }

    public static class console
    {
        public static Dictionary<string, DateTime> times = new Dictionary<string, DateTime>();

        public static bool timeEnabled;
        
        public static void time(string key,string text="")
        {
            if (!timeEnabled) return;

            if (times.ContainsKey(key))
            {
                var timeSpan = (DateTime.Now - times[key]).TotalSeconds;
                console.log($"{key} - {timeSpan.ToString("0.00000")} - {text}");
                times[key]=DateTime.Now;
            }
            else
            {
                console.log($"{key} - start - {text}");
                times.Add(key,DateTime.Now);
            }
        }
        public static void timeEnd(string key)
        {
            if (!timeEnabled) return;

            if (times.ContainsKey(key))
            {
                var timeSpan = (DateTime.Now - times[key]).TotalSeconds;
                console.log($"{key} - {timeSpan.ToString("0.00000")}");
                times[key] = DateTime.Now;
                times.Remove(key);
            }
        }
       

        public static string logFile;
        public static Action<string> logAction;
        private static void Log(string msg)
        {
            if (logAction != null)
                logAction(msg);
            else if (string.IsNullOrEmpty(logFile))
                Debug.Print(msg);
            else
                File.AppendAllText(logFile, msg + "\n");
        }
        public static void warn(params object[] msgs)
        {
            var sb = new StringBuilder();
            sb.Append("WARN! ");
            foreach (var msg in msgs)
                sb.Append((msg??"").ToString()+" ");
            Log(sb.ToString());
        }

       
        public static void log(params object[] msgs)
        {
            var sb = new StringBuilder();
            foreach (var msg in msgs)
                sb.Append((msg ?? "").ToString() + " ");
            Log(sb.ToString());
        }

        private static string errLogPath=System.IO.Path.Combine(System.IO.Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location),"ThreeLog.err");
        public static void error(params object[] msgs)
        {
            logFile = errLogPath;
            var sb = new StringBuilder();
            sb.Append("ERROR! ");
            foreach (var msg in msgs)
                sb.Append((msg ?? "").ToString() + " ");
            Log(sb.ToString());
            logFile = null;
        }
    }
}
